package com.example.demo.controller;

import com.example.demo.entity.LoginRequest;
import com.example.demo.entity.LoginResponse;
import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;
import com.example.demo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")  // 与前端接口路径保持一致
public class StudentAuthController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private JwtUtil jwtUtil;

    // 学生登录接口（与前端AuthApi的studentLogin方法匹配）
    @PostMapping("/login")
    public ResponseEntity<LoginResponse> studentLogin(@RequestBody LoginRequest request) {
        // 1. 验证学生信息
        Optional<Student> student = studentService.findStudentById(request.getUserId());
        if (student.isPresent() && student.get().getPassword().equals(request.getPassword())) {
            // 2. 生成JWT令牌
            String token = jwtUtil.generateToken(request.getUserId());
            // 3. 构建成功响应
            LoginResponse response = new LoginResponse(
                    true,
                    student.get().getStudentId(),
                    student.get().getStudentName(),
                    token
            );
            return ResponseEntity.ok(response);
        }
        // 登录失败（账号或密码错误）
        return ResponseEntity.status(401).body(new LoginResponse(false, null, null, null));
    }
}